package com.toKnow.controller;

import com.toKnow.model.entity.SourceAnswer;
import com.toKnow.model.entity.SourceComment;
import com.toKnow.model.entity.Source;
import com.toKnow.model.vo.*;
import com.toKnow.service.ServiceException;
import com.toKnow.service.SourceService;
import com.toKnow.utils.JwtUserSessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/api/source")
public class SourceController {
    @Autowired
    SourceService sourceService;

    public Integer getUid(HttpSession session){
        try{
            String token = (String) session.getAttribute("userToken");
            return Integer.parseInt(JwtUserSessionUtil.getInfo(token,"id"));
        } catch (Exception e){
            return null;
        }
    }

    @ResponseBody
    @RequestMapping(value = "",method = RequestMethod.POST)
    public BasicVo homeSearch(HttpServletRequest request,  HttpSession session, RestrictionVo restrictionVo){
        try{
            List<SourceAbstractVo> list=new ArrayList<>();
            List<Source> sources = sourceService.searchSource(getUid(session),restrictionVo);
            for (Source source : sources){
                Path fileAbsPath = Paths.get(request.getServletContext().getResource("/").getPath().substring(1), source.getFile());
                File file = fileAbsPath.toFile();
                Boolean flag = true;
                if(restrictionVo.getMaxsize() != null && file.length() / 1000 > restrictionVo.getMaxsize()) flag = false;
                if(restrictionVo.getMinsize() != null && file.length() / 1000 < restrictionVo.getMinsize()) flag = false;
                if(flag) list.add(new SourceAbstractVo(source));
            }
            return new BasicVo(true,null,list);
        }catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/content")//,method = RequestMethod.POST)
    public BasicVo getSource(HttpSession session,String source_id){
        if (source_id==null) return new BasicVo(false,"没有携带文章编号",null);
        // TestHelpUtil.fakeLogin(session,1);
        try{
            Integer sid=Integer.parseInt(source_id);
            Integer uid=getUid(session);
            Source source = sourceService.getSource(sid);
            if(source==null) return new BasicVo(false,"没有找到资源",null);
            SourceVo sourceVo = new SourceVo(source);
            if (uid!=null){
                sourceVo.setIs_like(sourceService.isLikeSource(uid,sid));
                sourceVo.setIs_collect(sourceService.isCollectSource(uid,sid));
                sourceVo.setIs_Buy(sourceService.isBuySource(uid,sid));
            }
            return new BasicVo(true,null,sourceVo);
        }catch (NumberFormatException e){
            return new BasicVo(false,"资源编号不为数字",null);
        }
        catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }
    @ResponseBody
    @RequestMapping(value = "/download")//,method = RequestMethod.POST)
    public BasicVo downloadSource(HttpSession session, String source_id){
        if (source_id==null) return new BasicVo(false,"没有携带资源编号",null);
        try{
            Integer uid=getUid(session),sid=Integer.parseInt(source_id);
            if (uid==null) return new BasicVo(false,"没有找到用户ID，可能是没有登录",null);
            if (sourceService.isBuySource(uid,sid)){
                sourceService.downloadSource(uid,sid);
                return new BasicVo(true,null,"还没有讨论传输资源的方案，这里假装有一个资源");
            }else{
                return new BasicVo(false,"你没有权限下载，请先购买",null);
            }
        }catch (NumberFormatException e){
            return new BasicVo(false,"文章编号不为数字",null);
        }catch (ServiceException e){
            return new BasicVo(false,e.getMessage(),null);
        }
        catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }

//    @ResponseBody
//    @RequestMapping(value = "/content/like",method = RequestMethod.POST)
//    public BasicVo likeSource(HttpSession session,String source_id){
//        if (source_id==null) return new BasicVo(false,"没有携带文章编号",null);
//        // TestHelpUtil.fakeLogin(session,1);
//        try{
//            Integer sid=Integer.parseInt(source_id);
//            Integer uid=getUid(session);
//            if (uid!=null){
//                if (sourceService.changeLikeSource(uid,sid)) return new BasicVo(true,null,null);
//                else return new BasicVo(false,"未知错误",null);
//            }else {
//                return new BasicVo(false,"没有找到用户ID，可能是没有登录",null);
//            }
//        }catch (NumberFormatException e){
//            return new BasicVo(false,"文章编号不为数字",null);
//        }catch (ServiceException e){
//            return new BasicVo(false,e.getMessage(),null);
//        }
//        catch (Exception e){
//            return new BasicVo(false,"未知错误",null);
//        }
//    }
    @ResponseBody
    @RequestMapping(value = "/content/collect",method = RequestMethod.POST)
    public BasicVo collectSource(HttpSession session,String source_id){
        if (source_id==null) return new BasicVo(false,"没有携带文章编号",null);
        // TestHelpUtil.fakeLogin(session,1);
        try{
            Integer sid=Integer.parseInt(source_id);
            Integer uid=getUid(session);
            if (uid!=null){
                if (sourceService.changeCollectSource(uid,sid)) return new BasicVo(true,null,null);
                else throw new RuntimeException("未知错误");
            }else {
                return new BasicVo(false,"没有找到用户ID，可能是没有登录",null);
            }
        }catch (NumberFormatException e){
            return new BasicVo(false,"文章编号不为数字",null);
        }catch (ServiceException e){
            return new BasicVo(false,e.getMessage(),null);
        } catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }
    @ResponseBody
    @RequestMapping(value = "/content/pay",method = RequestMethod.POST)
    public BasicVo buySource(HttpSession session,String source_id){
        if (source_id==null) return new BasicVo(false,"没有携带资源编号",null);
        // TestHelpUtil.fakeLogin(session,1);
        try{
            Integer sid=Integer.parseInt(source_id);
            Integer uid=getUid(session);
            if (uid!=null){
                if (sourceService.isBuySource(uid,sid)) return new BasicVo(false,"您已经购买过这个资源了",null);
                if (sourceService.buySource(uid,sid)) return new BasicVo(true,null,null);
                else throw new RuntimeException("未知错误");
            }else {
                return new BasicVo(false,"没有找到用户ID，可能是没有登录",null);
            }
        }catch (NumberFormatException e){
            return new BasicVo(false,"文章编号不为数字",null);
        }catch (ServiceException e){
            return new BasicVo(false,e.getMessage(),null);
        } catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }
    @RequestMapping(value = "/content/comment",method = RequestMethod.POST)
    @ResponseBody
    public BasicVo getComment(Integer source_id,Integer page){
        try {
            if (source_id == null) return new BasicVo(false, "没有携带文章编号", null);
            if (page == null || page < 0) return new BasicVo(false, "页码非法", null);
            List<SourceComment> comments = sourceService.getComment(source_id, page);
            List<CommentVo> ans = new ArrayList<>();
            for (SourceComment comment : comments) {
                ans.add(new CommentVo(comment));
            }
            return new BasicVo(true, null, ans);
        }catch (ServiceException e){
            return new BasicVo(false,e.getMessage(),null);
        } catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }
    @RequestMapping(value = "/content/comment/reply",method = RequestMethod.POST)
    @ResponseBody
    public BasicVo getAnswer (Integer comment_id,Integer page){
        try {
            if (comment_id == null) return new BasicVo(false, "没有携带文章编号", null);
            if (page == null || page < 0) return new BasicVo(false, "页码非法", null);
            List<SourceAnswer> answers = sourceService.getAnswer(comment_id, page);
            List<AnswerVo> ans = new ArrayList<>();
            for (SourceAnswer answer : answers) {
                ans.add(new AnswerVo(answer));
            }
            return new BasicVo(true, null, ans);
        }catch (ServiceException e){
            return new BasicVo(false,e.getMessage(),null);
        } catch (Exception e){
            return new BasicVo(false,"未知错误",null);
        }
    }
}
